package me.anharu.video_editor.filter

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import com.daasuu.mp4compose.filter.GlOverlayFilter
import me.anharu.video_editor.TextOverlay
import android.text.Layout
import android.text.StaticLayout
import android.text.TextPaint
import android.graphics.*


class GlTextOverlayFilter(textOverlay: TextOverlay) : GlOverlayFilter() {
    private val textOverlay: TextOverlay = textOverlay;

    protected override fun drawCanvas(canvas: Canvas) {
        val bitmap: Bitmap = textAsBitmap(textOverlay.text,textOverlay.size.toFloat(),textOverlay.color, textOverlay.width.toFloat(),textOverlay.height.toFloat(),textOverlay.align )
        canvas.drawBitmap(bitmap,textOverlay.x.toFloat(),textOverlay.y.toFloat(),null);
    }
    private fun textAsBitmap(text: String, textSize: Float, color: String, width:Float, height: Float, align: String): Bitmap {
        // val paint = Paint(Paint.ANTI_ALIAS_FLAG)
        val paint = Paint()
        //TODO : Use specified font - via. Typeface
        //TODO : Support Text Bold, Italic & Bold Italic - via. Typeface
        paint.textSize = textSize
        paint.color = Color.parseColor(color)
        //TODO : Support Center & Right Aligns
        //TODO : Support text will be out of video boundaries check
        //TODO : Support fallback align if text will be out of video boundaries

        // val baseline = -paint.ascent() // ascent() is negative
        val image = Bitmap.createBitmap(width.toInt(), height.toInt(), Bitmap.Config.ARGB_8888)
        val canvas = Canvas(image)
        paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_OVER)
        paint.textAlign = Paint.Align.LEFT
        var textAlign = Layout.Alignment.ALIGN_NORMAL
        if(align == "center"){
            textAlign = Layout.Alignment.ALIGN_CENTER
//            paint.textAlign = Paint.Align.CENTER
        }
        if(align == "right"){
            textAlign = Layout.Alignment.ALIGN_OPPOSITE;
//            paint.textAlign = Paint.Align.RIGHT
        }

        val rect = RectF(
            0.0.toFloat(),
            0.0.toFloat(),
            width,
            height
        )
        val textPaint = TextPaint(paint)
        val sl = StaticLayout(
            text,
            textPaint,
            rect.width().toInt(),
            textAlign,
            1.0f,
            1.0f,
            false
        )

        canvas.save()
        canvas.translate(rect.left, rect.top)

        sl.draw(canvas)
        canvas.restore()
        // canvas.drawText(text, 0f, baseline, paint)


        return image
    }
}